package com.itouch.bracelet.activity;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itouch.bracelet.R;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.bean.UpdateInfo;
import com.itouch.bracelet.bluetooth.BluetoothConstants;
import com.itouch.bracelet.bluetooth.BluetoothHandler;
import com.itouch.bracelet.bluetooth.BluetoothPacket;
import com.itouch.bracelet.bluetooth.BluetoothService;
import com.itouch.bracelet.bluetooth.BluetoothSpp;
import com.itouch.bracelet.bluetooth.BluetoothUtil;
import com.itouch.bracelet.bluetooth.BluetoothValue;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.MethodUtils;
import com.itouch.widget.SwitchButton;

/**
 * cocoaSJ
 */
public class SetActivity extends BaseActivity implements OnClickListener,OnCheckedChangeListener{

	private static final String LOG_TAG = "SetActivity";
	private RelativeLayout update;
	private RelativeLayout change_password;
	private RelativeLayout about_xiaoxi;
	private RelativeLayout change_devicecode;

	private SwitchButton sb1;
	private SwitchButton sb2;
	private SwitchButton sb3;
	private SwitchButton sb4;
	private SwitchButton sb5;
	private SwitchButton sb6;
	private SwitchButton sb7;
	private SwitchButton sb8;
	private TextView logout;
	private TextView updatetext;

	@Override
	protected int setContentViewById() {
		return R.layout.activity_set;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		LoginUser user = UserCache.getOauth(context);
		if (user == null) {
			this.finish();
		}
	}

	@Override
	protected void initViews() {
		updatetext= (TextView) findViewById(R.id.update_text);
		try{
			updatetext.setText(getString(R.string.update)+"(" + getVersionName()+")");
		}catch(Exception e){
			updatetext.setText(getString(R.string.update));
		}
		
		
		logout = (TextView) findViewById(R.id.logout);
		logout.setOnClickListener(this);

		update = (RelativeLayout) findViewById(R.id.update);
		update.setOnClickListener(this);
		change_password = (RelativeLayout) findViewById(R.id.change_password);
		change_password.setOnClickListener(this);

		about_xiaoxi = (RelativeLayout) findViewById(R.id.about_xiaoxi);
		about_xiaoxi.setOnClickListener(this);

		change_devicecode = (RelativeLayout) findViewById(R.id.change_devicecode);
		
		TextView devicecode_tv=(TextView) findViewById(R.id.devicecode_tv);
		devicecode_tv.setText("修改设备号 ("+UserCache.getOauth(this).getDeviceNo()+")");
		
		change_devicecode.setOnClickListener(this);

		
		
		sb1 = (SwitchButton) findViewById(R.id.sb1);
		
		sb1.setChecked(BluetoothValue.INSTANCE.isBluetoothStatus());
		
		sb1.setOnCheckedChangeListener(this);

		
		

		sb2 = (SwitchButton) findViewById(R.id.sb2);
		sb3 = (SwitchButton) findViewById(R.id.sb3);
		sb4 = (SwitchButton) findViewById(R.id.sb4);
		sb5 = (SwitchButton) findViewById(R.id.sb5);
		sb6 = (SwitchButton) findViewById(R.id.sb6);
		sb7 = (SwitchButton) findViewById(R.id.sb7);
		sb8 = (SwitchButton) findViewById(R.id.sb8);

		sb2.setOnCheckedChangeListener(this);
		sb3.setOnCheckedChangeListener(this);
		sb4.setOnCheckedChangeListener(this);
		sb5.setOnCheckedChangeListener(this);
		sb6.setOnCheckedChangeListener(this);
		sb7.setOnCheckedChangeListener(this);
		sb8.setOnCheckedChangeListener(this);

		RelativeLayout updatetime = (RelativeLayout) findViewById(R.id.updatetime);
		updatetime.setOnClickListener(this);

	}

	@Override
	protected void initData() {

		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothHandler.ACTION_STATUS);
		registerReceiver(receiver, filter);

		if(BluetoothValue.INSTANCE.stepStatus==null){
			BluetoothValue.INSTANCE.stepStatus=false;
		}
		if(BluetoothValue.INSTANCE.takeIncorrectStatus==null){
			BluetoothValue.INSTANCE.takeIncorrectStatus=false;
		}
		if(BluetoothValue.INSTANCE.braceletWarnStatus==null){
			BluetoothValue.INSTANCE.braceletWarnStatus=false;
		}
		
		if(BluetoothValue.INSTANCE.disConnecting){
			sb1.setEnabled(false);
		}
		
		if(BluetoothValue.INSTANCE.isBluetoothStatus()){
			sb2.setChecked(BluetoothValue.INSTANCE.stepStatus);
			sb6.setChecked(BluetoothValue.INSTANCE.braceletWarnStatus);
			sb7.setChecked(BluetoothValue.INSTANCE.takeIncorrectStatus);
		}else{
			sb2.setEnabled(false);
			sb6.setEnabled(false);
			sb7.setEnabled(false);
		}
		
		sb3.setChecked(BluetoothValue.INSTANCE.temperatureStatus);
		sb4.setChecked(BluetoothValue.INSTANCE.lowEnergyStatus);
		sb5.setChecked(BluetoothValue.INSTANCE.lostStatus);
		sb8.setChecked(BluetoothValue.INSTANCE.outOfRangeStatus);
		

	}

	@Override
	public void onClick(View v) {
		Intent it = null;
		switch (v.getId()) {
		case R.id.update:
			Toast.makeText(context, R.string.vsersion_checking,
					Toast.LENGTH_LONG).show();
			new Thread(CheckVersionTask).start();
			break;
		case R.id.logout:
			it = new Intent(context, ExitActivity.class);
			startActivity(it);
			break;
		case R.id.change_devicecode:
			it = new Intent(context, ChangeDeviceCodeActivity.class);
			startActivity(it);
			break;

		case R.id.about_xiaoxi:
			it = new Intent(context, BasicWebviewActivity.class);
			startActivity(it);
			break;

		case R.id.change_password:
			it = new Intent(context, ChangePasswordActivity.class);
			startActivity(it);
			break;
		case R.id.updatetime:
			if (BluetoothValue.INSTANCE.isBluetoothStatus()) {
				// 同步时间
				BluetoothPacket packet = new BluetoothPacket();
				int type = 1;// mother
				Date da = new Date();
				int year = da.getYear() + 1900;
				int month = da.getMonth() + 1;
				byte[] con3 = { (byte) 0xE3, (byte) (year >> 8), (byte) year,
						(byte) month, (byte) da.getDate(),
						(byte) da.getHours(), (byte) da.getMinutes(),
						(byte) da.getSeconds() };
				packet.setData(con3);
				if (BluetoothValue.INSTANCE.id != null) {
					packet.setId(BluetoothValue.INSTANCE.id);
				} else {
					Toast.makeText(this, "未连接手环，稍后再试！", Toast.LENGTH_SHORT)
							.show();
					return;
				}
				BluetoothUtil.packetData(packet, type);
				if (BluetoothSpp.getInstance().sendPacket(packet)) {
					Toast.makeText(SetActivity.this, "同步成功!",
							Toast.LENGTH_SHORT).show();
				}
				/*if (BluetoothSpp.getInstance().sendBluetoothPacket(packet)) {
					Toast.makeText(SetActivity.this, "同步成功!",
							Toast.LENGTH_SHORT).show();
				}*/
			} else {
				Toast.makeText(SetActivity.this, "请打开蓝牙开关后重试!",
						Toast.LENGTH_SHORT).show();
			}
			break;
		default:
			break;
		}

	}

	/*
	 * 从服务器获取xml解析并进行比对版本号
	 */
	private Runnable CheckVersionTask = new Runnable() {

		@Override
		public void run() {
			try {

				// 从资源文件获取服务器 地址
				String path = Constants.VERSION_XML;
				// 包装成url的对象
				URL url = new URL(path);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setConnectTimeout(5000);
				InputStream is = conn.getInputStream();
				infohaha = MethodUtils.getUpdataInfo(is);

				String versionname = getVersionName();
				Message msg = new Message();
				if (infohaha.getVersion().equals(versionname)) {
					msg.what = 0x123459;
				} else {
					
					msg.what = 0x123456;
					
				}
				handler.sendMessage(msg);
			} catch (Exception e) {
				// 待处理
				Message msg = new Message();
				msg.what = 0x234567;
				handler.sendMessage(msg);
				e.printStackTrace();
			}
		}
	};

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0x123456:
				// 对话框通知用户升级程序
				showUpdataDialog();
				break;
			case 0x234567:
				// 服务器超时
				Toast.makeText(getApplicationContext(), "获取服务器更新信息失败",
						Toast.LENGTH_SHORT).show();
				break;
			case 0x999999:
				// 下载apk失败
				Toast.makeText(getApplicationContext(), "下载新版本失败",
						Toast.LENGTH_SHORT).show();
				break;

			default:

				Toast.makeText(getApplicationContext(), "当前已是最新版本",
						Toast.LENGTH_SHORT).show();
				break;

			}
		}
	};
	private UpdateInfo infohaha;

	/*
	 * 
	 * 弹出对话框通知用户更新程序
	 * 
	 * 弹出对话框的步骤： 1.创建alertDialog的builder. 2.要给builder设置属性, 对话框的内容,样式,按钮
	 * 3.通过builder 创建一个对话框 4.对话框show()出来
	 */
	protected void showUpdataDialog() {
		AlertDialog.Builder builer = new Builder(this);
		builer.setTitle("版本升级");
		builer.setMessage(infohaha.getDescription());
		// 当点确定按钮时从服务器上下载 新的apk 然后安装
		builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				downLoadApk();
			}
		});
		builer.setNegativeButton("取消", null);

		AlertDialog dialog = builer.create();
		dialog.show();
	}

	/*
	 * 从服务器中下载APK
	 */
	protected void downLoadApk() {
		final ProgressDialog pd; // 进度条对话框
		pd = new ProgressDialog(this);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("正在下载更新");
		pd.show();
		new Thread() {
			@Override
			public void run() {
				try {
					File file = MethodUtils.getFileFromServer(
							Constants.VERSION_APK, pd);
					sleep(3000);
					installApk(file);
					pd.dismiss(); // 结束掉进度条对话框
				} catch (Exception e) {
					Message msg = new Message();
					msg.what = 0x999999;
					handler.sendMessage(msg);
					e.printStackTrace();
					pd.dismiss(); // 结束掉进度条对话框
				}
			}
		}.start();
	}

	// 安装apk
	protected void installApk(File file) {
		Intent intent = new Intent();
		// 执行动作
		intent.setAction(Intent.ACTION_VIEW);
		// 执行的数据类型
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}

	/*
	 * 获取当前程序的版本号
	 */
	private String getVersionName() throws Exception {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
				0);
		return packInfo.versionName;
	}


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);// 销毁
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			int status = intent.getIntExtra("status", -1);
			if (status == BluetoothConstants.MESSAGE_CONNECT_SUCCESS) {
				Toast.makeText(SetActivity.this, "连接成功！", Toast.LENGTH_SHORT)
						.show();
				sb1.setEnabled(true);
			} else if (status == BluetoothConstants.MESSAGE_CONNECT_FAILED) {
				Toast.makeText(SetActivity.this, "连接失败！", Toast.LENGTH_SHORT)
				.show();
			} else if (status == BluetoothConstants.MESSAGE_DISCONNECT_SUCCESS) {
				sb1.setEnabled(true);
			}
		}
	};

	@Override
	public void onCheckedChanged(CompoundButton cb, boolean state) {
		// TODO Auto-generated method stub
		SwitchButton sb=(SwitchButton) cb;
		switch (sb.getId()) {
		case R.id.sb1:
			
			if (state) {
				
				String[] devices=UserCache.getOauth(this).getDeviceNo().split(":");
				if(devices.length!=6){
					Toast.makeText(this, "设备号错误，请修改后重试！", Toast.LENGTH_SHORT)
					.show();
					sb1.setChecked(false);
					return;
				}else{
					
					int part1=Integer.valueOf(devices[4], 16);
					int part2=Integer.valueOf(devices[5], 16);
					byte[] ids={(byte)part1,(byte)part2};
					BluetoothValue.INSTANCE.id=ids;
						
					
				}
				
				
				BluetoothValue.INSTANCE.setBluetoothStatus(state);
				
				BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
				if (adapter == null) {
					Toast.makeText(this, "该设备不支持蓝牙！", Toast.LENGTH_SHORT)
							.show();
				} else {
					if (adapter.enable()) {
						
						sb2.setEnabled(true);
						sb6.setEnabled(true);
						sb7.setEnabled(true);
						
						// open
						Intent in = new Intent(SetActivity.this,
								BluetoothService.class);
						in.putExtra("address", UserCache.getOauth(SetActivity.this).getDeviceNo());
						startService(in);
					} else {
						Toast.makeText(this, "蓝牙尚未打开，请打开后重试！",
								Toast.LENGTH_SHORT).show();
						Intent enabler = new Intent(
								BluetoothAdapter.ACTION_REQUEST_ENABLE);
						startActivity(enabler);
					}
				}

			} else {
				//关闭需要时间
				sb1.setEnabled(false);
				
				//关闭手环蓝牙
				BluetoothPacket packet=new BluetoothPacket();
				int type=1;//mother
				byte[] con={(byte) 0xE8,0};
				packet.setData(con);
				
				if (BluetoothValue.INSTANCE.id != null) {
					packet.setId(BluetoothValue.INSTANCE.id);
				} else {
					Toast.makeText(this, "未连接手环，稍后再试！", Toast.LENGTH_SHORT)
							.show();
					BluetoothSpp.getInstance().disconnect();
					return;
				}
				BluetoothUtil.packetData(packet, type);
				BluetoothSpp.getInstance().sendPacket(packet);
				
				sb2.setEnabled(false);
				sb6.setEnabled(false);
				sb7.setEnabled(false);
				
				BluetoothSpp.getInstance().disconnect();
				
/*				Intent in = new Intent(SetActivity.this, BluetoothService.class);
				stopService(in);
				*/
				
			}
			break;
		case R.id.sb2:
			if(BluetoothValue.INSTANCE.isBluetoothStatus()){
				//计步器开关
				BluetoothPacket packet=new BluetoothPacket();
				int type=1;//mother
				if(state){
					byte[] con={(byte) 0xE0,1};
					packet.setData(con);
				}else{
					byte[] con={(byte) 0xE0,0};
					packet.setData(con);
				}
				
				if (BluetoothValue.INSTANCE.id != null) {
					packet.setId(BluetoothValue.INSTANCE.id);
				} else {
					Toast.makeText(this, "未连接手环，稍后再试！", Toast.LENGTH_SHORT)
							.show();
					return;
				}
				BluetoothUtil.packetData(packet, type);
				BluetoothSpp.getInstance().sendPacket(packet);
				
				BluetoothValue.INSTANCE.stepStatus = state;
			}else{
				Toast.makeText(this, "未打开蓝牙开关，请稍后再试！", Toast.LENGTH_SHORT)
				.show();
				sb.slideToChecked(false);
			}
			break;
		case R.id.sb3:
			SharedPreferences sp2 = getSharedPreferences("Bluetooth",
					context.MODE_PRIVATE);
			Editor editor2 = sp2.edit();
			editor2.putBoolean("temperature", state);
			editor2.commit();
			BluetoothValue.INSTANCE.temperatureStatus = state;
			break;
		case R.id.sb4:
			SharedPreferences sp3 = getSharedPreferences("Bluetooth",
					context.MODE_PRIVATE);
			Editor editor3 = sp3.edit();
			editor3.putBoolean("lowenergy", state);
			editor3.commit();
			BluetoothValue.INSTANCE.lowEnergyStatus = state;
			break;
		case R.id.sb5:
			SharedPreferences sp4 = getSharedPreferences("Bluetooth",
					context.MODE_PRIVATE);
			Editor editor4 = sp4.edit();
			editor4.putBoolean("lost", state);
			editor4.commit();
			BluetoothValue.INSTANCE.lostStatus = state;
			break;
		case R.id.sb8:
			SharedPreferences sp5 = getSharedPreferences("Bluetooth",
					context.MODE_PRIVATE);
			Editor editor5 = sp5.edit();
			editor5.putBoolean("outofrange", state);
			editor5.commit();
			BluetoothValue.INSTANCE.outOfRangeStatus = state;
			break;
		case R.id.sb6:

			if(BluetoothValue.INSTANCE.isBluetoothStatus()){
				//超出范围报警
				BluetoothPacket packet=new BluetoothPacket();
				int type=1;//mother
				if(state){
					byte[] con={(byte) 0xE4,3};
					packet.setData(con);
				}else{
					byte[] con={(byte) 0xE4,0};
					packet.setData(con);
				}
				
				if (BluetoothValue.INSTANCE.id != null) {
					packet.setId(BluetoothValue.INSTANCE.id);
				} else {
					Toast.makeText(this, "未连接手环，稍后再试！", Toast.LENGTH_SHORT)
							.show();
					return;
				}
				BluetoothUtil.packetData(packet, type);
				BluetoothSpp.getInstance().sendPacket(packet);
				
			}else{
				Toast.makeText(this, "未打开蓝牙开关，请稍后再试！", Toast.LENGTH_SHORT)
				.show();
				sb.slideToChecked(false);
			}
			
			BluetoothValue.INSTANCE.braceletWarnStatus = state;
			break;
		case R.id.sb7:
			if(BluetoothValue.INSTANCE.isBluetoothStatus()){
				//防抱错模式开关
				BluetoothPacket packet=new BluetoothPacket();
				int type=1;//mother
				if(state){
					byte[] con={(byte) 0xE2,(byte)1,(byte)3};
					packet.setData(con);
				}else{
					byte[] con={(byte) 0xE2,(byte)0,(byte)0};
					packet.setData(con);
				}
				
				if (BluetoothValue.INSTANCE.id != null) {
					packet.setId(BluetoothValue.INSTANCE.id);
				} else {
					Toast.makeText(this, "未连接手环，稍后再试！", Toast.LENGTH_SHORT)
							.show();
					return;
				}
				BluetoothUtil.packetData(packet, type);
				BluetoothSpp.getInstance().sendPacket(packet);
				
				BluetoothValue.INSTANCE.takeIncorrectStatus = state;
			}else{
				Toast.makeText(this, "未打开蓝牙开关，请稍后再试！", Toast.LENGTH_SHORT)
				.show();
				sb.slideToChecked(false);
			}
			break;
		}
	}

}
